<template>
  <view class="warehouse-container">
    <!-- A. 页面头部 -->
    <view class="page-header">
      <text class="page-title">炉次检验作业</text>
    </view>

    <!-- B. 主信息区 -->
    <view class="plan-form-container">
      <view class="section-header">
        <text class="section-title">作业设定</text>
      </view>

      <view class="form-section">
        <view class="form-row">
          <view
            class="form-group"
            style="flex-direction: row; align-items: center"
          >
            <text
              class="form-label"
              style="margin-right: 20rpx; margin-bottom: 0"
              >生产工序</text
            >
            <picker
              mode="selector"
              :range="processOptions"
              range-key="text"
              :value="currentProcessIndex"
              @change="handleProcessChange"
              class="form-picker"
              style="flex: 1"
            >
              <view class="picker-content">
                <text>{{
                  currentProcess && currentProcess.processName
                    ? currentProcess.processName
                    : "请选择生产工序"
                }}</text>
                <text class="picker-arrow">▼</text>
              </view>
            </picker>
          </view>
        </view>

        <view class="form-row">
          <view
            class="form-group"
            style="flex-direction: row; align-items: baseline; flex: 1"
          >
            <text class="form-label" style="margin-right: 10px">班别：</text>
            <text class="form-value">{{ workClass || "未设置" }}</text>
          </view>
          <view
            class="form-group"
            style="
              flex-direction: row;
              align-items: baseline;
              flex: 1;
              margin-left: 20px;
            "
          >
            <text class="form-label" style="margin-right: 10px">班次：</text>
            <text class="form-value">{{ workShift || "未设置" }}</text>
          </view>
        </view>

        <view class="form-row">
          <view class="form-group" style="flex: none; width: 100%">
            <text class="form-label">操作备注</text>
            <input
              type="text"
              class="form-input"
              placeholder="请输入操作备注"
              style="
                border: 1px solid #e0e0e0;
                border-radius: 6px;
                padding: 8px;
                background-color: #fafafa;
                resize: vertical;
                min-height: 60px;
                font-size: 14px;
                line-height: 1.4;
              "
              v-model.trim="formData.busMemo"
            />
          </view>
        </view>
      </view>
    </view>

    <!-- C. 计划查询与作业记录TAB区域 -->
    <view class="plan-form-container">
      <view class="form-section">
        <view class="form-row">
          <view class="form-group" style="flex: none; width: 100%">
            <!-- 使用统一扫码输入组件 -->
            <ScanInput
              v-model="searchForm.searchCode"
              placeholder="1.请输入炉号"
              tip-text="支持扫描炉号"
              :loading="false"
              :on-scan-result="handleScanResult"
              :on-confirm="handleScanConfirm"
              ref="scanInputRef"
            />
          </view>
        </view>
      </view>
    </view>
    <view class="plan-form-container">
      <!-- TAB页切换 -->
      <view class="tab-container">
        <view
          class="tab-item"
          :class="{ active: activeTab === 'operation' }"
          @click="activeTab = 'operation'"
        >
          2.质检记录
        </view>
      </view>

      <!-- 作业记录TAB内容 -->
      <view v-if="activeTab === 'operation'" class="tab-content">
        <!-- 产品下线内容 -->
        <view class="form-section">
          <view class="form-row">
            <view class="form-group">
              <text class="form-label">炉次号</text>
              <input
                type="text"
                class="form-input"
                placeholder="炉次号"
                v-model.trim="furnaceNoDisplay"
                :disabled="true"
                style="width: 100%"
              />
            </view>
          </view>
          <view class="form-row">
            <view class="form-group" style="flex: none; width: 100%">
              <text class="form-label">批次</text>
              <view style="display: flex; align-items: center; gap: 8px">
                <input
                  type="text"
                  class="form-input"
                  placeholder="请点击批次打印自动生成"
                  v-model.trim="formData.batchNo"
                  style="flex: 1"
                />
                <button class="btn-submit" @click="handlePrintBatch">
                  批次打印
                </button>
              </view>
            </view>
          </view>
          <view class="form-row">
            <view class="form-group" style="flex: none; width: 100%">
              <text class="form-label">取样编号</text>
              <input
                type="text"
                class="form-input"
                placeholder="炉号-qm1"
                v-model.trim="formData.sampleCode"
                style="width: 100%"
              />
            </view>
          </view>

          <view class="form-row">
            <view class="form-group">
              <text class="form-label">钢种</text>
              <input
                type="text"
                class="form-input"
                placeholder="钢种"
                v-model.trim="formData.steelGradeName"
              />
            </view>
            <view class="form-group">
              <text class="form-label">规格</text>
              <input
                type="text"
                class="form-input"
                placeholder="规格"
                v-model.trim="formData.prodSpec"
              />
            </view>
          </view>
        </view>

        <!-- 3. 质检结果录入区域 -->
        <view class="form-section" style="margin-top: 20rpx">
          <view class="section-header" style="margin-bottom: 20rpx">
            <text class="section-title">3. 化学成分检验结果</text>
          </view>

        <view class="form-row standard-select-row">
          <view class="form-group" style="flex-direction: column; align-items: stretch; width: 100%">
            <view class="standard-label-row">
              <text class="form-label" style="margin-bottom: 0">标准匹配</text>
              <text
                class="standard-status"
                v-if="chemicalStandardLoading || chemicalDetailLoading"
              >
                {{ chemicalDetailLoading ? "明细加载中..." : "匹配中..." }}
              </text>
            </view>
            <picker
              mode="selector"
              :range="chemicalStandards"
              range-key="standName"
              :value="standardPickerValue"
              :disabled="chemicalStandards.length === 0"
              @change="handleStandardPickerChange"
            >
              <view class="picker-content" style="width: 100%; margin-bottom: 10rpx">
                <text style="flex: 1; text-align: left">{{
                  selectedStandardDisplayText
                }}</text>
                <text class="picker-arrow">▼</text>
              </view>
            </picker>
            <view
              class="standard-meta"
              v-if="selectedChemicalStandard"
            >
              <text>标准号：{{ selectedChemicalStandard.standNo || "-" }}</text>
              <text>版本：{{ selectedChemicalStandard.standName || "-" }}</text>
              <text>品名：{{ selectedChemicalStandard.prodName || "-" }}</text>
            </view>
            <view
              class="standard-meta standard-empty"
              v-else
            >
              <text>{{
                formData.steelGradeName ? "暂无匹配标准" : "请先查询钢种"
              }}</text>
            </view>
            <view class="standard-actions">
              <button class="btn-secondary" @click="manualReloadStandards">
                重新匹配
              </button>
            </view>
          </view>
        </view>

          <!-- 化学成分检验结果表格 -->
          <view class="chemical-table-container">
            <view class="table-header">
              <view class="header-cell" style="flex: 0.4">序号</view>
              <view class="header-cell" style="flex: 0.5">化学成分</view>
              <view class="header-cell" style="flex: 1.2">检验结果</view>
            <view class="header-cell standard-range-header" style="flex: 4.5">标准要求</view>
              <view class="header-cell" style="flex: 0.7">单位</view>
              <view class="header-cell" style="flex: 0.5">操作</view>
            </view>
            <view class="table-body" style="max-height: 500rpx; overflow-y: auto">
              <!-- 预设化学成分行 -->
              <view
                class="table-row"
                v-for="(item, index) in chemicalItemList"
                :key="'item-' + index"
              >
                <view class="table-cell" style="flex: 0.4">{{ index + 1 }}</view>
                <view class="table-cell" style="flex: 0.5; justify-content: flex-start">
                  <!-- 预设行：直接显示化学成分名称 -->
                  <text v-if="item.isPreset" style="font-weight: 500; color: #333; font-size: 26rpx">{{ item.chemitemName }}</text>
                  <!-- 自定义行：可以输入自定义成分 -->
                  <view v-else style="display: flex; flex-direction: column; gap: 6rpx; width: 100%">
                    <picker
                      mode="selector"
                      :range="presetChemicalItems"
                      range-key="name"
                      :value="item.presetIndex >= 0 ? item.presetIndex : -1"
                      @change="(e) => handlePresetChemicalChange(e, index)"
                    >
                      <view class="picker-content" style="min-height: 50rpx; padding: 6rpx 10rpx">
                        <text style="flex: 1; text-align: left; font-size: 24rpx">{{ item.chemitemName || "请选择" }}</text>
                        <text class="picker-arrow">▼</text>
                      </view>
                    </picker>
                    <input
                      type="text"
                      class="table-input"
                      placeholder="或输入自定义成分"
                      :value="item.customChemitemName"
                      @blur="(e) => handleCustomChemicalInput(e, index)"
                      @input="(e) => { 
                        item.customChemitemName = e.detail.value;
                        if (e.detail.value && e.detail.value.trim()) {
                          item.chemitemName = e.detail.value.trim();
                          item.chemitemCode = e.detail.value.trim();
                          item.presetIndex = -1;
                        }
                      }"
                      style="font-size: 22rpx; padding: 6rpx 8rpx; margin-top: 4rpx"
                    />
                  </view>
                </view>
                <view class="table-cell" style="flex: 1.2">
                  <input
                    type="text"
                    class="table-input"
                    placeholder="请输入检验结果"
                    v-model.trim="item.chemitemValue"
                    @blur="(e) => validateChemicalValue(e, index)"
                    style="text-align: center"
                  />
                </view>
                <view class="table-cell standard-range-cell" style="flex: 10.5; justify-content: flex-start; align-items: stretch;">
                  <view
                    v-if="item.standardRangeText"
                    class="standard-range-text"
                  >
                    {{ item.standardRangeText }}
                  </view>
                  <text v-else class="standard-range-empty">标准：--</text>
                </view>
                <view class="table-cell" style="flex: 0.7">
                  <text>{{ item.meterUnit || "%" }}</text>
                </view>
                <view class="table-cell" style="flex: 0.5">
                  <!-- 预设行不显示删除按钮，自定义行显示删除按钮 -->
                  <view
                    v-if="!item.isPreset"
                    class="btn-delete-small"
                    @tap="handleRemoveChemicalItem(index)"
                    style="padding: 4rpx 12rpx; font-size: 22rpx; cursor: pointer"
                  >
                    删除
                  </view>
                  <text v-else style="color: #ccc">-</text>
                </view>
              </view>
            </view>
          </view>

          <!-- 添加项目按钮移到底部 -->
          <view style="margin-top: 20rpx; text-align: center">
            <view 
              class="btn-add" 
              @tap.stop="handleAddChemicalItem" 
              @click.stop="handleAddChemicalItem"
              style="padding: 12rpx 24rpx; font-size: 26rpx; min-width: 120rpx; cursor: pointer; pointer-events: auto; position: relative; z-index: 100; display: inline-block"
            >
              + 添加自定义项目
            </view>
          </view>
        </view>

        <!-- D. 按钮操作区 -->
        <view class="button-row">
          <button class="btn-reset" @click="handleReset">重置</button>
          <button class="btn-submit" @click="handleOffline">4. 保存</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
// 导入API方法
import { getProcessOptions } from "@/api/md/process";
// 导入炼轧半成品库存API
import { LzProdStockRealApi } from "@/api/warehouse/lzprodstockreal";
// 导入质检记录API
import { PesSampleApi } from "@/api/qm/pessample";
// 导入化学成分API
import { ChemicalItemApi } from "@/api/qm/chemicalitem";
import { ChemicalRequirApi } from "@/api/qm/chemicalrequir";

// 导入统一扫码输入组件
import ScanInput from "@/components/ScanInput";

import { dateHelperApi } from "@/pages/smart/warehouse/utils/date-helper";
import { pdaScanApi } from "@/pages/smart/pdaScan";
export default {
  name: "StockIn",
  mixins: [pdaScanApi],
  components: {
    ScanInput,
  },

  data() {
    return {
      // 表单数据
      formData: {
        currentDate: dateHelperApi.getCurrentDate(),
        processCode: "",
        processName: "",
        // 基础字段
        furnaceNo: "", // 炉次号
        operationMemo: "", // 操作备注
        workStaff: "", // 配渣工

        // 产出作业字段
        batchNo: "", // 批次号
        steelGradeName: "", // 钢种
        prodSpec: "", // 规格
        sampleCode: "", // 取样编号
      },
      // 扫码查询表单
      searchForm: {
        searchCode: "", // 扫码内容
      },
      // 扫码加载状态（已取消）
      scanLoading: false,

      // 当前工序信息
      currentProcess: {
        processCode: "",
        processName: "请选择生产工序",
      },
      // 班次班组信息
      workShift: "", // 班次
      workClass: "", // 班组

      // 工序选项列表
      processOptions: [],
      // 当前工序索引
      currentProcessIndex: -1,
      // 炉次信息表格数据
      furnaceTable: [],
      // 炉次号显示
      furnaceNoDisplay: "",

      // TAB切换状态
      activeTab: "operation", // 当前激活的标签页: plan-计划设定, record-作业记录

      // 质检记录相关
      chemicalItemList: [], // 化学成分检验结果列表
      chemicalItemOptions: [], // 化学成分选项列表（从API获取，备用）
      // 预设化学成分列表
      presetChemicalItems: [
        { name: "C", code: "C" },
        { name: "P", code: "P" },
        { name: "S", code: "S" },
        { name: "Mn", code: "Mn" },
        { name: "Si", code: "Si" },
        { name: "Cr", code: "Cr" },
        { name: "Ni", code: "Ni" },
        { name: "Al", code: "Al" },
        { name: "Fe", code: "Fe" },
        { name: "Nb", code: "Nb" },
        { name: "Cu", code: "Cu" },
        { name: "Y", code: "Y" },
        { name: "Ce", code: "Ce" },
        { name: "Hf", code: "Hf" },
        { name: "Mo", code: "Mo" },
        { name: "Re", code: "Re" },
        { name: "Ti", code: "Ti" },
        { name: "N", code: "N" },
        { name: "Zr", code: "Zr" },
        { name: "Co", code: "Co" },
      ],
      // 取样实绩相关字段
      sampleCode: "", // 取样编号（自动生成）
      steelGradeCode: "", // 钢种编码
      standCode: "", // 标准编码
      standName: "", // 标准名称

      // 化学成分标准匹配
      chemicalStandards: [], // 牌号主表
      chemicalStandardLoading: false,
      chemicalDetailLoading: false,
      selectedChemicalStandardIndex: -1,
      selectedChemicalStandard: null,
      chemicalStandardDetails: [],
      chemicalStandardDetailMap: {},
    };
  },
  computed: {
    // 日期工具命名空间（供模板使用）
    dateHelperApi() {
      return dateHelperApi;
    },
    standardPickerValue() {
      return this.selectedChemicalStandardIndex >= 0
        ? this.selectedChemicalStandardIndex
        : 0;
    },
    selectedStandardDisplayText() {
      if (this.selectedChemicalStandard) {
        const { standName, standNo, steelGradeName } =
          this.selectedChemicalStandard;
        const base = standName || standNo || "已匹配标准";
        return steelGradeName ? `${base}（${steelGradeName}）` : base;
      }
      if (this.chemicalStandardLoading) {
        return "匹配中...";
      }
      if (this.formData.steelGradeName) {
        return "未匹配到标准";
      }
      return "请先获取钢种";
    },
  },
  async onLoad() {
    await this.loadProcessOptions(); // 加载工序选项
    this.loadCurrentProcess(); // 加载当前工序
    // 初始化PDA打印模块（来自mixin）
    this.initScanModule();
    // 加载化学成分选项列表
    await this.loadChemicalItemOptions();
    // 初始化预设化学成分列表
    this.initPresetChemicalItems();
  },
  beforeDestroy() {
    // 停止PDA扫码，释放资源（来自mixin）
    this.stopPdaScan();
  },
  methods: {
    // 扫码结果处理
    handleScanResult(result) {
      // 预处理扫码结果
      if (result && result.length > 0) {
        this.searchForm.searchCode = result;
        this.handleScanConfirm();
      }
    },

    // 扫码确认查询
    async handleScanConfirm() {
      if (!this.searchForm.searchCode.trim()) {
        uni.showToast({
          title: "请输入炉号",
          icon: "none",
        });
        return;
      }

      try {
        // 根据扫码内容判断查询类型并调用相应接口
        const searchCode = this.searchForm.searchCode.trim();

        // 调用炉号查询接口
        const params = {
          furnaceNo: searchCode, // 使用炉号作为查询参数
          pageNo: 1,
          pageSize: 100,
        };

        // 如果当前工序已选择，添加工序名称参数
        if (this.formData.processName) {
          params.processName = this.formData.processName;
        }

        const response = await LzProdStockRealApi.getLzProdStockRealPage(
          params
        );

        if (response.code === 0) {
          //将查询结果的第一行赋值给form相关字段
          if (
            response.data &&
            response.data.list &&
            response.data.list.length > 0
          ) {
            const firstItem = response.data.list[0];
            // 批次号
            this.formData.batchNo = firstItem.batchNo || "";
            // 炉号
            this.formData.furnaceNo = firstItem.furnaceNo || "";
            this.furnaceNoDisplay = firstItem.furnaceNo || "";
            // 钢种
            this.formData.steelGradeName = firstItem.steelGradeName || "";
            // 规格
            this.formData.prodSpec = firstItem.prodSpec || "";
            // 业务备注
            this.formData.busMemo = firstItem.busMemo || "";
            // 自动生成取样编号
            this.formData.sampleCode = this.generateSampleCode();
            // 根据钢种匹配化学成分标准
            this.loadChemicalStandardsBySteel();
            uni.showToast({
              title: `查询成功`,
              icon: "success",
            });
          } else {
            uni.showToast({
              title: "未查询到相关数据",
              icon: "none",
            });
          }
        } else {
          uni.showToast({
            title: response.msg || "查询失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("查询炉号信息失败:", error);
        this.formData.batchNo = "";
        this.formData.furnaceNo = "";
        this.furnaceNoDisplay = "";
        this.formData.steelGradeName = "";
        this.formData.prodSpec = "";
        this.formData.sampleCode = "";
        this.resetChemicalStandardState();
        uni.showToast({
          title: "查询炉号信息失败",
          icon: "none",
        });
      }
    },

    /* 加载当前工序 */
    loadCurrentProcess() {
      // 尝试从用户配置中加载缓存的工序信息
      const userData = this.$store.state.user;
      const userConfig = userData.userConfig || {};
      if (userData && userData.userConfig) {
        const userConfig = userData.userConfig;
        // 从缓存中加载工序信息
        if (userConfig.processNo && userConfig.processName) {
          this.currentProcess = {
            processCode: userConfig.processNo,
            processName: userConfig.processName,
          };
          this.formData.processCode = userConfig.processNo;
          this.formData.processName = userConfig.processName;

          // 加载班次班组信息
          this.workShift = userConfig.workShift || "";
          this.workClass = userConfig.workClass || "";

          // 在工序选项中找到对应的索引
          const processIndex = this.processOptions.findIndex(
            (item) => item.value === userConfig.processNo
          );
          if (processIndex !== -1) {
            this.currentProcessIndex = processIndex;
          }
          return;
        }
      }

      // 如果没有缓存或缓存无效，默认选择第一个工序
      if (this.processOptions.length > 0) {
        this.currentProcess = {
          processCode: this.processOptions[0].value,
          processName: this.processOptions[0].text,
        };
        this.formData.processCode = this.currentProcess.processCode;
        this.formData.processName = this.currentProcess.processName;
        this.currentProcessIndex = 0;
      }
    },

    // 加载工序选项
    async loadProcessOptions() {
      try {
        const options = await getProcessOptions();
        this.processOptions = options;
        console.log("生产工序选项加载成功:", this.processOptions);
      } catch (error) {
        // 静默处理错误
        console.error("加载工序选项失败:", error);
        this.processOptions = [];
      }
    },

    /* 处理工序选择变化 */
    handleProcessChange(e) {
      const index = e.detail.value;
      this.currentProcessIndex = index;
      const selectedProcess = this.processOptions[index];
      if (selectedProcess) {
        this.currentProcess = {
          processCode: selectedProcess.value,
          processName: selectedProcess.text,
        };
        this.formData.processCode = selectedProcess.value;
        this.formData.processName = selectedProcess.text;
      }
    },

    /* ========= 化学成分标准匹配 ========= */
    async loadChemicalStandardsBySteel(showFeedback = false) {
      if (!this.formData.steelGradeName) {
        this.resetChemicalStandardState();
        if (showFeedback) {
          uni.showToast({
            title: "暂无钢种信息",
            icon: "none",
          });
        }
        return;
      }
      this.chemicalStandardLoading = true;
      try {
        // 清理钢种名称，去除首尾空格
        const steelGradeName = this.formData.steelGradeName.trim();
        console.log("开始查询化学成分标准，钢种名称:", steelGradeName);
        
        // 先尝试不带busStatus的查询（更宽松）
        const queryParams = {
          pageNo: 1,
          pageSize: 50, // 增加查询数量
          steelGradeName: steelGradeName,
        };
        
        console.log("查询参数:", JSON.stringify(queryParams));
        
        const response = await ChemicalRequirApi.getChemicalRequirPage(queryParams);
        
        console.log("标准查询响应:", {
          code: response.code,
          msg: response.msg,
          total: response.data?.total || 0,
          listLength: response.data?.list?.length || 0,
          list: response.data?.list || []
        });
        
        if (response.code === 0 && response.data) {
          let standards = response.data.list || [];
          
          // 如果查询结果为空，尝试不传steelGradeName查询所有（用于调试）
          if (standards.length === 0) {
            console.log("按钢种名称查询无结果，尝试查询所有标准（用于调试）");
            const allResponse = await ChemicalRequirApi.getChemicalRequirPage({
              pageNo: 1,
              pageSize: 10,
            });
            if (allResponse.code === 0 && allResponse.data) {
              console.log("所有标准列表（前10条）:", allResponse.data.list);
              console.log("请检查数据库中是否有钢种名称为:", steelGradeName, "的标准记录");
            }
          }
          
          // 如果有busStatus字段，可以进一步过滤生效状态
          // 但先不过滤，看看能否查到数据
          this.chemicalStandards = standards;
          
          if (this.chemicalStandards.length > 0) {
            const newIndex =
              this.selectedChemicalStandardIndex >= 0
                ? this.selectedChemicalStandardIndex
                : 0;
            const safeIndex = Math.min(
              newIndex,
              this.chemicalStandards.length - 1
            );
            await this.setSelectedChemicalStandardByIndex(safeIndex);
            if (showFeedback) {
              uni.showToast({
                title: `找到${this.chemicalStandards.length}条标准`,
                icon: "success",
              });
            }
          } else {
            this.resetChemicalStandardState();
            if (showFeedback) {
              uni.showToast({
                title: `未找到钢种"${steelGradeName}"的匹配标准`,
                icon: "none",
                duration: 3000,
              });
            }
          }
        } else {
          this.resetChemicalStandardState();
          console.error("标准查询失败:", response);
          uni.showToast({
            title: response.msg || "标准查询失败",
            icon: "none",
            duration: 3000,
          });
        }
      } catch (error) {
        console.error("加载化学成分标准失败:", error);
        this.resetChemicalStandardState();
        uni.showToast({
          title: "标准查询失败: " + (error.message || "未知错误"),
          icon: "none",
          duration: 3000,
        });
      } finally {
        this.chemicalStandardLoading = false;
      }
    },

    async setSelectedChemicalStandardByIndex(index) {
      if (
        !this.chemicalStandards ||
        this.chemicalStandards.length === 0 ||
        index < 0 ||
        index >= this.chemicalStandards.length
      ) {
        this.selectedChemicalStandardIndex = -1;
        this.selectedChemicalStandard = null;
        this.chemicalStandardDetails = [];
        this.chemicalStandardDetailMap = {};
        this.applyStandardsToChemicalList();
        return;
      }

      this.selectedChemicalStandardIndex = index;
      this.selectedChemicalStandard = this.chemicalStandards[index];
      this.standCode = this.selectedChemicalStandard.standCode || "";
      this.standName = this.selectedChemicalStandard.standName || "";
      this.steelGradeCode = this.selectedChemicalStandard.steelGradeCode || "";

      if (this.selectedChemicalStandard.id) {
        await this.fetchChemicalStandardDetails(this.selectedChemicalStandard.id);
      } else {
        this.chemicalStandardDetails = [];
        this.chemicalStandardDetailMap = {};
        this.applyStandardsToChemicalList();
      }
    },

    async fetchChemicalStandardDetails(chemrequirId) {
      if (!chemrequirId) {
        this.chemicalStandardDetails = [];
        this.chemicalStandardDetailMap = {};
        this.applyStandardsToChemicalList();
        return;
      }
      this.chemicalDetailLoading = true;
      try {
        const response =
          await ChemicalRequirApi.getChemicalRequirDetailPage({
            pageNo: 1,
            pageSize: 200,
            chemrequirId,
          });
        if (response.code === 0 && response.data) {
          this.chemicalStandardDetails = response.data.list || [];
        } else {
          this.chemicalStandardDetails = [];
          uni.showToast({
            title: response.msg || "标准明细查询失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("加载化学成分标准明细失败:", error);
        this.chemicalStandardDetails = [];
        uni.showToast({
          title: "标准明细查询失败",
          icon: "none",
        });
      } finally {
        this.chemicalDetailLoading = false;
        this.chemicalStandardDetailMap = this.buildStandardDetailMap(
          this.chemicalStandardDetails
        );
        this.applyStandardsToChemicalList();
      }
    },

    handleStandardPickerChange(e) {
      const index = parseInt(e.detail.value, 10);
      if (isNaN(index)) {
        return;
      }
      this.setSelectedChemicalStandardByIndex(index);
    },

    async manualReloadStandards() {
      await this.loadChemicalStandardsBySteel(true);
    },

    resetChemicalStandardState() {
      this.chemicalStandards = [];
      this.selectedChemicalStandardIndex = -1;
      this.selectedChemicalStandard = null;
      this.chemicalStandardDetails = [];
      this.chemicalStandardDetailMap = {};
      this.standCode = "";
      this.standName = "";
      this.steelGradeCode = "";
      this.applyStandardsToChemicalList();
    },

    buildStandardDetailMap(detailList = []) {
      const map = {};
      detailList.forEach((detail) => {
        const keys = [];
        if (detail.chemitemCode) {
          keys.push(detail.chemitemCode);
        }
        if (detail.chemitemName) {
          keys.push(detail.chemitemName);
        }
        keys.forEach((key) => {
          const norm = this.normalizeChemKey(key);
          if (norm) {
            if (map[norm]) {
              // 合并已存在的记录：将多条记录的上限和下限合并到一条
              const existing = map[norm];
              // 合并 lower：如果已存在的为空，而新的有值，则使用新的
              const hasExistingLower = existing.lower !== null && existing.lower !== undefined && existing.lower !== "";
              const hasNewLower = detail.lower !== null && detail.lower !== undefined && detail.lower !== "";
              if (!hasExistingLower && hasNewLower) {
                existing.lower = detail.lower;
                existing.lowCompare = detail.lowCompare || existing.lowCompare;
              }
              // 合并 upper：如果已存在的为空，而新的有值，则使用新的
              const hasExistingUpper = existing.upper !== null && existing.upper !== undefined && existing.upper !== "";
              const hasNewUpper = detail.upper !== null && detail.upper !== undefined && detail.upper !== "";
              if (!hasExistingUpper && hasNewUpper) {
                existing.upper = detail.upper;
                existing.upCompare = detail.upCompare || existing.upCompare;
              }
              // 保留其他字段（如果已存在的为空，使用新的）
              if (!existing.meterUnit && detail.meterUnit) {
                existing.meterUnit = detail.meterUnit;
              }
              if (!existing.analyMethod && detail.analyMethod) {
                existing.analyMethod = detail.analyMethod;
              }
              if (!existing.decimalPrecision && detail.decimalPrecision) {
                existing.decimalPrecision = detail.decimalPrecision;
              }
            } else {
              // 首次遇到该化学成分，直接存储
              map[norm] = { ...detail };
            }
          }
        });
      });
      return map;
    },

    normalizeChemKey(value) {
      return value && value.trim() ? value.trim().toUpperCase() : "";
    },

    applyStandardsToChemicalList() {
      if (!Array.isArray(this.chemicalItemList)) {
        return;
      }
      this.chemicalItemList.forEach((_, index) => {
        this.applyStandardForItem(index);
      });
    },

    applyStandardForItem(index) {
      const item = this.chemicalItemList[index];
      if (!item) {
        return;
      }
      const matchedDetail = this.matchStandardDetail(item);
      const updatedItem = { ...item };
      if (matchedDetail) {
        const lower = this.safeToNumber(matchedDetail.lower);
        const upper = this.safeToNumber(matchedDetail.upper);
        updatedItem.lower = lower;
        updatedItem.upper = upper;
        updatedItem.lowCompare =
          matchedDetail.lowCompare || (lower !== null ? ">=" : "");
        updatedItem.upCompare =
          matchedDetail.upCompare || (upper !== null ? "<=" : "");
        updatedItem.meterUnit =
          matchedDetail.meterUnit ||
          updatedItem.meterUnit ||
          matchedDetail.reserveVarchar1 ||
          "%";
        updatedItem.standardRangeText = this.formatStandardRange(
          matchedDetail,
          updatedItem.meterUnit
        );
        updatedItem.analyMethod = matchedDetail.analyMethod || "";
        updatedItem.decimalPrecision = matchedDetail.decimalPrecision || 2;
      } else {
        updatedItem.lower = null;
        updatedItem.upper = null;
        updatedItem.lowCompare = "";
        updatedItem.upCompare = "";
        updatedItem.standardRangeText = "";
      }
      this.$set(this.chemicalItemList, index, updatedItem);
    },

    matchStandardDetail(item) {
      if (!this.chemicalStandardDetailMap) {
        return null;
      }
      const candidates = [];
      if (item.chemitemCode) {
        candidates.push(item.chemitemCode);
      }
      if (
        item.chemitemName &&
        item.chemitemName !== item.chemitemCode
      ) {
        candidates.push(item.chemitemName);
      }
      for (const value of candidates) {
        const key = this.normalizeChemKey(value);
        if (key && this.chemicalStandardDetailMap[key]) {
          return this.chemicalStandardDetailMap[key];
        }
      }
      return null;
    },

    safeToNumber(value) {
      if (value === null || value === undefined || value === "") {
        return null;
      }
      const numberValue = Number(value);
      return isNaN(numberValue) ? null : numberValue;
    },

    formatStandardRange(detail, unitText = "") {
      const parts = [];
      const lower = detail.lower;
      const upper = detail.upper;
      if (lower !== null && lower !== undefined && lower !== "") {
        parts.push(`${detail.lowCompare || ">="}${lower}`);
      }
      if (upper !== null && upper !== undefined && upper !== "") {
        parts.push(`${detail.upCompare || "<="}${upper}`);
      }
      if (parts.length === 0) {
        return unitText ? `标准：-- ${unitText}` : "标准：--";
      }
      return `标准：${parts.join(" ， ")} ${unitText}`.trim();
    },

    // PDA打印方法
    pdaPrint(batchNo, spec, printTime) {
      try {
        // 调用原生打印方法
        const result = this.handlePdaPrint(batchNo, spec, printTime);
        return result;
      } catch (error) {
        console.error("PDA打印失败:", error);
        return false;
      }
    },

    // 批次打印
    async handlePrintBatch() {
      if (!this.formData.batchNo) {
        uni.showToast({
          title: "请先创建批次",
          icon: "none",
        });
        return;
      }

      try {
        console.log("批次打印参数:", {
          batchNo: this.formData.batchNo,
          steelGradeName: this.formData.steelGradeName,
          printTime: dateHelperApi.getCurrentDate(),
        });

        // 调用PDA打印接口
        const printResult = this.pdaPrint(
          this.formData.batchNo, // 批次号
          this.formData.steelGradeName + "/" + this.formData.prodSpec || "", // 规格
          dateHelperApi.getCurrentDate() // 打印时间
        );

        if (printResult) {
          uni.showToast({
            title: "批次打印成功",
            icon: "success",
          });
        } else {
          uni.showToast({
            title: "批次打印失败，请检查设备",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("批次打印失败:", error);
        uni.showToast({
          title: "批次打印失败，请重试",
          icon: "none",
        });
      }
    },

    // 表格滚动到底部加载更多
    onReachBottom() {
      // 数据加载功能已取消
    },

    // 数字验证
    validateNumber(event, obj, field) {
      const value = parseFloat(event.detail.value);
      if (isNaN(value) || value < 0) {
        obj[field] = "";
        uni.showToast({
          title: "请输入有效的数字",
          icon: "none",
        });
      } else {
        obj[field] = value;
      }
    },

    // 重置表单
    handleReset() {
      // 保留工序信息
      const processCode = this.formData.processCode;
      const processName = this.formData.processName;
      
      // 重置表单数据
      this.formData = {
        currentDate: dateHelperApi.getCurrentDate(),
        processCode: processCode,
        processName: processName,
        // 基础字段
        furnaceNo: "", // 炉次号
        operationMemo: "", // 操作备注
        workStaff: "", // 配渣工
        // 产出作业字段
        batchNo: "", // 批次号
        steelGradeName: "", // 钢种
        prodSpec: "", // 规格
        busMemo: "", // 业务备注
        sampleCode: "", // 取样编号
      };
      
      // 重置查询表单
      this.searchForm = {
        searchCode: "", // 扫码内容
      };
      
      // 重置炉次号显示
      this.furnaceNoDisplay = "";
      
      // 重置质检记录相关（重新初始化预设列表）
      this.sampleCode = "";
      this.steelGradeCode = "";
      this.standCode = "";
      this.standName = "";
      // 重新初始化预设化学成分列表
      this.initPresetChemicalItems();
      this.resetChemicalStandardState();
      
      uni.showToast({
        title: "表单已重置",
        icon: "success",
      });
    },

    // 加载化学成分选项列表
    async loadChemicalItemOptions() {
      try {
        const response = await ChemicalItemApi.getSimpleList();
        if (response.code === 0 && response.data) {
          this.chemicalItemOptions = response.data || [];
        }
      } catch (error) {
        console.error("加载化学成分选项失败:", error);
        this.chemicalItemOptions = [];
      }
    },

    // 初始化预设化学成分列表
    initPresetChemicalItems() {
      // 将预设的20个化学成分添加到列表中
      this.chemicalItemList = this.presetChemicalItems.map((item, index) => ({
        chemitemCode: item.code || item.name,
        chemitemName: item.name,
        chemitemValue: "",
        lower: null,
        upper: null,
        meterUnit: "%", // 默认单位
        analyMethod: "",
        decimalPrecision: 2, // 默认精度2位
        lowCompare: "",
        upCompare: "",
        presetIndex: index, // 预设选项索引
        customChemitemName: "", // 自定义化学成分名称
        isPreset: true, // 标记为预设项
        standardRangeText: "",
      }));
      console.log("初始化预设化学成分列表，共", this.chemicalItemList.length, "项");
      this.applyStandardsToChemicalList();
    },

    // 添加化学成分检验项目（自定义项）
    handleAddChemicalItem() {
      console.log("添加自定义化学成分项目 - 点击事件触发");
      console.log("添加前列表长度:", this.chemicalItemList.length);
      
      const newItem = {
        chemitemCode: "",
        chemitemName: "",
        chemitemValue: "",
        lower: null,
        upper: null,
        meterUnit: "%", // 默认单位
        analyMethod: "",
        decimalPrecision: 2, // 默认精度2位
        lowCompare: "",
        upCompare: "",
        presetIndex: -1, // 预设选项索引
        customChemitemName: "", // 自定义化学成分名称
        isPreset: false, // 标记为自定义项
        standardRangeText: "",
      };
      
      this.chemicalItemList.push(newItem);
      this.applyStandardForItem(this.chemicalItemList.length - 1);
      console.log("添加后列表长度:", this.chemicalItemList.length);
      
      // 滚动到底部（uni-app方式）
      this.$nextTick(() => {
        // 使用uni.createSelectorQuery来查询元素并滚动
        const query = uni.createSelectorQuery().in(this);
        query.select('.table-body').boundingClientRect((data) => {
          if (data) {
            uni.pageScrollTo({
              scrollTop: data.bottom,
              duration: 300
            });
          }
        }).exec();
      });
    },

    // 删除化学成分检验项目
    handleRemoveChemicalItem(index) {
      this.chemicalItemList.splice(index, 1);
      this.applyStandardsToChemicalList();
    },

    // 预设化学成分选择变化
    handlePresetChemicalChange(e, index) {
      const selectedIndex = e.detail.value;
      const selectedItem = this.presetChemicalItems[selectedIndex];
      if (selectedItem) {
        this.chemicalItemList[index].presetIndex = selectedIndex;
        this.chemicalItemList[index].chemitemCode = selectedItem.code || selectedItem.name;
        this.chemicalItemList[index].chemitemName = selectedItem.name;
        // 清空自定义输入
        this.chemicalItemList[index].customChemitemName = "";
        // 设置默认单位
        if (!this.chemicalItemList[index].meterUnit) {
          this.chemicalItemList[index].meterUnit = "%";
        }
        this.applyStandardForItem(index);
      }
    },

    // 自定义化学成分输入
    handleCustomChemicalInput(e, index) {
      const customName = e.detail.value ? e.detail.value.trim() : "";
      if (customName) {
        // 如果输入了自定义名称，使用自定义名称
        this.chemicalItemList[index].chemitemName = customName;
        this.chemicalItemList[index].chemitemCode = customName;
        // 重置预设选择
        this.chemicalItemList[index].presetIndex = -1;
        // 设置默认单位
        if (!this.chemicalItemList[index].meterUnit) {
          this.chemicalItemList[index].meterUnit = "%";
        }
      } else if (this.chemicalItemList[index].presetIndex < 0) {
        // 如果清空了自定义输入且没有选择预设，清空名称
        this.chemicalItemList[index].chemitemName = "";
        this.chemicalItemList[index].chemitemCode = "";
      }
      this.applyStandardForItem(index);
    },

    // 验证检验结果值
    validateChemicalValue(e, index) {
      const value = parseFloat(e.detail.value);
      const item = this.chemicalItemList[index];
      
      if (e.detail.value && !isNaN(value)) {
        // 检查是否在范围内
        if (item.lower !== null && value < item.lower) {
          uni.showToast({
            title: `${item.chemitemName}检验结果低于下限值`,
            icon: "none",
          });
        }
        if (item.upper !== null && value > item.upper) {
          uni.showToast({
            title: `${item.chemitemName}检验结果高于上限值`,
            icon: "none",
          });
        }
      }
    },

    // 生成取样编号：格式为"炉号-qm1"
    generateSampleCode() {
      if (!this.formData.furnaceNo || this.formData.furnaceNo.trim() === "") {
        return "";
      }
      return `${this.formData.furnaceNo.trim()}-qm1`;
    },

    // 处理炉号变化，自动更新取样编号（如果用户没有手动编辑过）
    handleFurnaceNoChange() {
      if (!this.formData.furnaceNo || this.formData.furnaceNo.trim() === "") {
        // 如果炉号为空，清空取样编号
        this.formData.sampleCode = "";
        return;
      }
      
      const newSampleCode = this.generateSampleCode();
      
      // 如果取样编号为空，自动生成
      if (!this.formData.sampleCode || this.formData.sampleCode.trim() === "") {
        this.formData.sampleCode = newSampleCode;
        return;
      }
      
      // 如果取样编号等于应该生成的编号，说明是自动生成的，自动更新
      if (this.formData.sampleCode === newSampleCode) {
        return; // 已经是正确的了，不需要更新
      }
      
      // 检查是否是自动生成的格式（以旧炉号开头且以-qm1结尾）
      // 如果是，则自动更新为新炉号的格式
      // 如果不是，说明用户手动编辑过，不自动更新
      const oldFurnaceNo = this.formData.sampleCode.split("-")[0];
      if (this.formData.sampleCode.endsWith("-qm1") && oldFurnaceNo) {
        // 是自动生成的格式，自动更新
        this.formData.sampleCode = newSampleCode;
      }
      // 否则不更新，保留用户手动编辑的值
    },

    // 保存质检记录
    async handleOffline() {
      // 校验必填字段
      if (!this.formData.furnaceNo) {
        uni.showToast({
          title: "请先查询炉号",
          icon: "none",
        });
        return;
      }

      if (this.chemicalItemList.length === 0) {
        uni.showToast({
          title: "请至少添加一个检验项目",
          icon: "none",
        });
        return;
      }

      // 校验检验结果是否填写（只校验有填写检验结果的行）
      const validItems = [];
      for (let i = 0; i < this.chemicalItemList.length; i++) {
        const item = this.chemicalItemList[i];
        // 只保存填写了检验结果的项目
        if (item.chemitemValue && item.chemitemValue.trim() !== "") {
          // 检查化学成分名称
          if (!item.chemitemName || item.chemitemName.trim() === "") {
            uni.showToast({
              title: `第${i + 1}行请选择或输入化学成分`,
              icon: "none",
            });
            return;
          }
          // 如果没有编码，使用名称作为编码
          if (!item.chemitemCode || item.chemitemCode.trim() === "") {
            item.chemitemCode = item.chemitemName;
          }
          validItems.push(item);
        }
      }

      // 至少需要一个有效的检验结果
      if (validItems.length === 0) {
        uni.showToast({
          title: "请至少填写一个检验结果",
          icon: "none",
        });
        return;
      }

      // 校验取样编号
      if (!this.formData.sampleCode || this.formData.sampleCode.trim() === "") {
        uni.showToast({
          title: "请输入取样编号",
          icon: "none",
        });
        return;
      }

      try {
        uni.showLoading({
          title: "保存中...",
        });

        // 使用用户编辑的取样编号
        const sampleCode = this.formData.sampleCode.trim();

        // 1. 创建取样实绩（PesSample）
        const pesSampleData = {
          // 注意：创建时不传id，让数据库自动生成
          sampleCode: sampleCode,
          furnaceNo: this.formData.furnaceNo,
          batchNo: this.formData.batchNo,
          steelGradeName: this.formData.steelGradeName,
          steelGradeCode: this.steelGradeCode || "",
          standCode: this.standCode || "",
          standName: this.standName || "",
          busMemo: this.formData.busMemo || "",
          busStatus: "生效",
        };

        console.log("准备创建取样实绩，数据：", pesSampleData);
        console.log("请求URL：/qm/pes-sample/create");
        console.log("完整请求数据（JSON）：", JSON.stringify(pesSampleData, null, 2));

        const sampleResponse = await PesSampleApi.createPesSample(pesSampleData);
        
        console.log("创建取样实绩响应：", sampleResponse);

        if (sampleResponse.code !== 0) {
          uni.hideLoading();
          uni.showToast({
            title: sampleResponse.msg || "创建取样实绩失败",
            icon: "none",
          });
          return;
        }

        const sampleId = sampleResponse.data;

        // 2. 批量创建质检结果明细（PesSampleItem）- 只保存有检验结果的项目
        const createItemPromises = validItems.map((item) => {
          const itemData = {
            sampleId: sampleId,
            sampleCode: sampleId, // 注意：根据后端DO定义，sampleCode是Long类型，这里使用sampleId
            furnaceNo: this.formData.furnaceNo,
            batchNo: this.formData.batchNo,
            steelGradeName: this.formData.steelGradeName,
            steelGradeCode: this.steelGradeCode || "",
            standCode: this.standCode || "",
            standName: this.standName || "",
            chemitemCode: item.chemitemCode,
            chemitemName: item.chemitemName,
            chemitemValue: item.chemitemValue,
            lower: item.lower,
            upper: item.upper,
            meterUnit: item.meterUnit || "",
            analyMethod: item.analyMethod || "",
            decimalPrecision: item.decimalPrecision,
            lowCompare: item.lowCompare || "",
            upCompare: item.upCompare || "",
            busStatus: "生效",
          };
          return PesSampleApi.createPesSampleItem(itemData);
        });

        const itemResponses = await Promise.all(createItemPromises);

        // 检查是否有失败的
        const failedItems = itemResponses.filter((res) => res.code !== 0);
        if (failedItems.length > 0) {
          uni.hideLoading();
          uni.showToast({
            title: `有${failedItems.length}个检验项目保存失败`,
            icon: "none",
          });
          return;
        }

        uni.hideLoading();
        uni.showToast({
          title: "保存成功",
          icon: "success",
        });

        // 保存成功后重置表单（保留工序信息）
        setTimeout(() => {
          this.handleReset();
        }, 1500);
      } catch (error) {
        console.error("保存质检记录失败:", error);
        uni.hideLoading();
        uni.showToast({
          title: "保存失败，请重试",
          icon: "none",
        });
      }
    },
  },
};
</script>

<style lang="scss">
@import "~@/pages/smart/scss/create.scss";

// 化学成分检验结果表格样式
.chemical-table-container {
  background: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  margin-top: 20rpx;

  .table-header {
    display: flex;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 20rpx 0;
    border-bottom: 2rpx solid rgba(255, 255, 255, 0.2);

    .header-cell {
      text-align: center;
      color: #000;
      font-size: 26rpx;
      font-weight: 600;
      padding: 0 8rpx;
      // flex值由内联样式控制，不在此处设置
    }
  }

  .table-body {
    .table-row {
      display: flex;
      align-items: center;
      border-bottom: 1rpx solid #f0f0f0;
      padding: 16rpx 0;
      transition: background-color 0.2s;

      &:hover {
        background-color: #f8f9fa;
      }

      &:last-child {
        border-bottom: none;
      }

      .table-cell {
        text-align: center;
        font-size: 24rpx;
        color: #333;
        padding: 8rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        min-height: 60rpx;
        // flex值由内联样式控制，不在此处设置

        .picker-content {
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: 100%;
          padding: 8rpx 12rpx;
          background: #f8f9fa;
          border: 2rpx solid #e0e0e0;
          border-radius: 8rpx;
          font-size: 24rpx;
          color: #495057;
          min-height: 60rpx;
          box-sizing: border-box;

          .picker-arrow {
            color: #999;
            font-size: 20rpx;
            margin-left: 8rpx;
            flex-shrink: 0;
          }
        }

        .table-input {
          width: 100%;
          padding: 8rpx 12rpx;
          background: #fff;
          border: 2rpx solid #e0e0e0;
          border-radius: 8rpx;
          font-size: 24rpx;
          text-align: center;
          color: #333;

          &:focus {
            border-color: #667eea;
            outline: none;
          }
        }

        .btn-delete-small {
          padding: 6rpx 16rpx;
          background: #ff4757;
          color: #fff;
          border: none;
          border-radius: 6rpx;
          font-size: 22rpx;
          cursor: pointer;
          transition: all 0.2s;
          user-select: none;
          -webkit-user-select: none;
          display: inline-flex;
          align-items: center;
          justify-content: center;
          white-space: nowrap;

          &:active {
            background: #ff3742;
            transform: scale(0.95);
          }
        }
      }
    }
  }
}

.standard-select-row {
  margin-bottom: 20rpx;

  .standard-label-row {
    display: flex;
    align-items: center;
    gap: 12rpx;
    margin-bottom: 12rpx;
  }

  .standard-status {
    font-size: 22rpx;
    color: #ff9f43;
  }

  .standard-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
    font-size: 24rpx;
    color: #666;
    margin-bottom: 12rpx;

    &.standard-empty {
      color: #bbb;
    }
  }

  .standard-actions {
    display: flex;
    justify-content: flex-end;
  }
}

.standard-range-text {
  font-size: 22rpx;
  color: #333;
  line-height: 1.4;
  padding: 6rpx 10rpx;
  border-radius: 6rpx;
  background: #f6f8ff;
  border: 2rpx dashed #b8c4ff;
  width: 100%;
  box-sizing: border-box;
  word-break: break-word;
  white-space: normal;
}

.standard-range-cell {
  flex-direction: column;
  align-items: stretch !important;
  justify-content: flex-start !important;
  min-width: 60%; // 允许 flex 收缩
}

.standard-range-empty {
  font-size: 22rpx;
  color: #ccc;
}

.btn-add {
  padding: 12rpx 24rpx;
  background: linear-gradient(135deg, #28a745, #20c997);
  color: #fff !important;
  border: none;
  border-radius: 8rpx;
  font-size: 26rpx;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  user-select: none;
  -webkit-user-select: none;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2rpx 8rpx rgba(40, 167, 69, 0.3);
  position: relative;
  z-index: 100;
  pointer-events: auto !important;
  -webkit-tap-highlight-color: transparent;

  &:active {
    background: linear-gradient(135deg, #218838, #1e7e34);
    transform: scale(0.95);
    box-shadow: 0 1rpx 4rpx rgba(40, 167, 69, 0.2);
  }

  &:hover {
    box-shadow: 0 4rpx 12rpx rgba(40, 167, 69, 0.4);
  }
}

.btn-secondary {
  padding: 10rpx 20rpx;
  background: #eef2ff;
  color: #4a5fd1;
  border: 2rpx solid #c7d2fe;
  border-radius: 8rpx;
  font-size: 24rpx;
  cursor: pointer;
  transition: all 0.2s;
  min-width: 140rpx;

  &:active {
    background: #dbe4ff;
  }
}

.empty-tip {
  text-align: center;
  padding: 40rpx;
  color: #999;
  font-size: 26rpx;
}
</style>
